﻿using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace isky.Plugin
{
    public class UpdatePreSalesorderPlugin : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {

            // Obtain the execution context service from the service provider.
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the Organization Service factory service from the service provider
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity preEntity = context.InputParameters["Target"] as Entity;
                    Entity PreImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains("PreImage")) ? context.PreEntityImages["PreImage"] : null;
                    Guid entityId = context.PrimaryEntityId; if (entityId == Guid.Empty) return;
                    Guid userId = context.UserId; if (userId == Guid.Empty) return;
                    Guid historyEntityId = Guid.Empty;

                    #region 将报价利润金额转成英文
                    if (preEntity.Contains("new_totalprofit"))
                    {
                        double totalus = preEntity.GetAttributeDefaultValue<double>("new_totalprofit", 0);
                        SalesOrderYGCBSql salesOrderYGCBSql = new SalesOrderYGCBSql();
                        if (totalus == 0)
                        {
                            preEntity.Attributes["new_totalprofitenglish"] = "ZERO";
                        }
                        else
                        {
                            string totalusEnglish = salesOrderYGCBSql.NumberToString((double)totalus);
                            preEntity.Attributes["new_totalprofitenglish"] = totalusEnglish.ToUpper();
                        }
                    }

                    #endregion


                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
                throw new NotImplementedException();
            }
        }

    }
}
